package ru.aptu.gsp_banking.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import ru.aptu.gsp_banking.domain.Account;
import ru.aptu.gsp_banking.domain.Currency;
import ru.aptu.gsp_banking.domain.Payment;
import ru.aptu.gsp_banking.service.AccountService;
import ru.aptu.gsp_banking.service.CurrencyService;
import ru.aptu.gsp_banking.service.PaymentService;

import java.security.Principal;
import java.util.List;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: alex
 * Date: 1/27/12
 * Time: 1:09 PM
 */

@Controller
public class PaymentController {

    @Autowired
    private AccountService accountService;

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private CurrencyService currencyService;

    private boolean posted = false;

    @ModelAttribute("accounts")
    public List<Account> listAccounts(Principal principal) {
        final String currentUser = principal.getName();
        return accountService.listAccount(currentUser);
    }

    @ModelAttribute("currencies")
    public List<Currency> listCurrencies() {
        return currencyService.listCurrency();
    }

    @RequestMapping(value = "/payments", method = RequestMethod.POST)
    public String paymentsPost() {
        posted = true;
        return "redirect:payments";
    }

    @RequestMapping(value = "/payments", method = RequestMethod.GET)
    public String paymentsGet(Map<String, Object> map) {
        if (!posted) {
            return "redirect:logout";
        }
        posted = false;

        Payment payment = new Payment();
        map.put("payment", payment);
        return "payments";
    }

    @RequestMapping(value = "/submit_payment", method = RequestMethod.POST)
    public String submitPayment(@ModelAttribute("payment") Payment payment, BindingResult result) {
        boolean paymentResult = paymentService.submitPayment(payment);
        if (paymentResult)
            return "redirect:/request_success";
        else
            return "redirect:/request_fail";
    }
}
